package com.medic.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.medic.service.interf.WXServiceInterface;
import com.medic.util.CacheUtil;
import com.medic.util.EncryptUtil;
import com.medic.util.HttpUtil;
import com.medic.util.JsonUtil;
import com.medic.util.StringUtil;

@Service("wxService")
public class WXServiceImpl implements WXServiceInterface {

	/**
	 * 微信获取签名需要的键名称
	 */
	private final String ticketKey = "jsapi_ticket";
	private final String nonceKey = "noncestr";
	private final String timestampKey = "timestamp";
	private final String urlKey = "url";
	private final String tokenKey = "access_token";
	private final String mediaIdKey = "media_id";
	private final String touserKey = "touser";
	private final String templateKey = "template_id";
	private final String dataKey = "data";
	private final String msgIdKey = "msgid";

	@Override
	public String getSignature(String url, String noncestr, long timestamp) throws Exception {
		String str = "";
		str = str + ticketKey + "=" + CacheUtil.getJsapiTicket() + "&" + nonceKey + "=" + noncestr + "&" + timestampKey
				+ "=" + String.valueOf(timestamp) + "&" + urlKey + "=" + url;
		System.out.println(str);
		return EncryptUtil.SHA1(str);
	}

	@Override
	public String downImg(String mediaId, String path, String fileName) throws Exception {
		String url = CacheUtil.getConfig().getProperty(StringUtil.DOWN_MEDIA_URL) + tokenKey + "="
				+ CacheUtil.getAccessToken() + "&" + mediaIdKey + "=" + mediaId;
		return HttpUtil.getReq(url, path, fileName);
	}

	@Override
	public boolean pushTempMsg(String tempId, String touser, String url, String data) throws Exception {
		boolean result = false;
		Map<String, String> map = new HashMap<String, String>();
		map.put(touserKey, touser);
		map.put(templateKey, tempId);
		map.put(urlKey, url);
		map.put(dataKey, data);
		String resJson = HttpUtil.postReq(CacheUtil.getConfig().getProperty(StringUtil.PUSH_TEMP_MSG_URL) + tokenKey + "="
				+ CacheUtil.getAccessToken(), map);
		String msgId = JsonUtil.getValue(resJson, msgIdKey);
		if(msgId != null && !msgId.equals("")){
			result = true;
		}
		return result;
	}

}
